import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/components/components'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

const useIndexHooks = () => {
  // 加载动画
  const isLoading = ref(true)
  // banner轮播列表
  const bannerList = ref<BannerItem[]>([])
  // 分类列表
  const categoryList = ref<CategoryItem[]>([])
  // 推荐列表
  const hotList = ref<HotItem[]>([])
  // 猜你喜欢组件实例
  const guessRef = ref<XtxGuessInstance>()
  // 下拉动画
  const isTriggered = ref(false)
  // 获取banner轮播数据
  const getHomeBannerData = async () => {
    const res = await getHomeBannerAPI()
    bannerList.value = res.result
  }

  // 获取分类列表数据
  const getCateGoryData = async () => {
    const res = await getHomeCategoryAPI()
    categoryList.value = res.result
  }

  // 获取热门列表
  const getHotData = async () => {
    const res = await getHomeHotAPI()
    hotList.value = res.result
  }

  // 触底加载更多数据
  const onScrolltolower = () => {
    guessRef.value?.getMore()
  }

  // 下拉刷新
  const onRefresherrefresh = async () => {
    // 开启动画
    isTriggered.value = true
    isLoading.value = true
    // 重置数据
    guessRef.value?.resetData()
    await Promise.all([
      getHomeBannerData(),
      getCateGoryData(),
      getHotData(),
      guessRef.value?.getMore(),
    ])

    // 关闭动画
    isTriggered.value = false
    isLoading.value = false
  }

  onLoad(async () => {
    Promise.all([getHomeBannerData(), getCateGoryData(), getHotData()])
    isLoading.value = false
  })

  return {
    bannerList,
    categoryList,
    hotList,
    guessRef,
    isLoading,
    isTriggered,
    onScrolltolower,
    onRefresherrefresh,
  }
}

export default useIndexHooks
